#include "SqliteDao.h"
#include <QtSql>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlQuery>
#include "TimeEntity.h"

SqliteDao::SqliteDao()
{
    initDB();
}
SqliteDao::~SqliteDao()
{
    release();
    printf("===release db===");
}

SqliteDao *SqliteDao::instance(){
    if(sqlDao == 0){
        sqlDao = new SqliteDao();
    }
    return sqlDao;
}
void SqliteDao::release(){
    sqlDao->db.close();
}
QList<TimeEntity> *SqliteDao::sqlQuery(){
//    printf("===query===\n");
    query->prepare("select * from time_list");
    QList<TimeEntity> *twList = new QList<TimeEntity>();
    if(!query->exec()){
        printf("查询表time_list失败\n");
    }else{
        while(query->next()){
            TimeEntity tw;
            tw.title = query->value(0).toString();
            tw.hour = query->value(1).toInt();
            tw.minute = query->value(2).toInt();
            tw.second = query->value(3).toInt();
            tw.refreshTime = query->value(4).toInt();
            twList->append(tw);
//            tw.toString();
        }
    }
    return twList;
}
void SqliteDao::sqlDelete(QString *title){
//    printf("===sqlDelete===\n");
    query->prepare("delete from time_list where title=?");
    query->addBindValue(*title);
    query->exec();
}
void SqliteDao::sqlInsert(TimeEntity *data){
//    printf("===insert===\n");
//    data->toString();
    query->prepare("insert into time_list values(?,?,?,?,?)");
    query->addBindValue(data->title);
    query->addBindValue(data->hour);
    query->addBindValue(data->minute);
    query->addBindValue(data->second);
    query->addBindValue(data->refreshTime);
    query->exec();
//    bool flag = query->exec();
//    printf("===insert--%s--===\n",flag?"success":"faild");
}

void SqliteDao::sqlCreateTable(){
//    printf("===sqlCreateTable===\n");
//    QStringList ts = db.tables();
    //当前就一张表，这么判断就行。
    if(db.tables().size() > 0){
        printf("===sqlCreateTable tables:%s===\n",db.tables().at(0).toUtf8().data());
        return;
    }
    query->exec("create table time_list("
                    "title varchar(20),"
                    "hour int,"
                    "minute int,"
                    "second int,"
                    "refresh_time int"
                ")");
}

void SqliteDao::initDB(){
//    printf("===initDB===\n");
    db = QSqlDatabase::addDatabase("QSQLITE");
//    如果使用sqlite数据库不想产生数据库文件，可以创建内存数据库。
//    db.setDatabaseName(":memory:");
    db.setDatabaseName("sqliteTimeList.db");
    if(!db.open()){
        printf("sqlite数据库打开失败!\n");
        QMessageBox::critical(nullptr,
                    QObject::tr("打开数据库失败"),
                    QObject::tr("无法建立数据库连接.\n"
                                "请查阅、搜索帮助 Qt SQL driver\n"
                                "点击'返回'以退出"),
                    QMessageBox::Cancel);
        return;
    }
    query = new QSqlQuery(db);
    sqlCreateTable();
}
//在"stdio.h"里有定义 其实NULL 就是0.
//SqliteDao *SqliteDao::sqlDao = NULL;
SqliteDao *SqliteDao::sqlDao = 0;
